package com.qf.dao.daoImpl;

import com.qf.dao.BookDao;
import com.qf.entity.Book;
import com.qf.entity.Page;
import com.qf.util.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 常肖飞先生
 * @version V1.0
 * @Project 0511_3
 * @Package com.qf.dao.daoImpl
 * @Description: 图书 daoimpl层
 * @Date 2022/5/12 10:46
 */
public class BookDaoImpl implements BookDao {
    private QueryRunner qr = new QueryRunner(DBUtil.getDateSource());

    @Override
    public List<Book> selectAll() {
        String sql = "select * from t_books";
        try {
            return qr.query(sql, new BeanListHandler<>(Book.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Book> selectAllByPage(Page page) {
        String sql = "select * from t_books limit ?,?";
        try {
            List<Book> list = qr.query(sql, new BeanListHandler<Book>(Book.class), page.getStartRows(), page.getPageSize());
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int selectAllByPageCount() {
        String sql = "select count(*) from t_books";
        try {
            long count = qr.query(sql, new ScalarHandler<Long>());
            return (int)count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int addOneBook(Book book) {
        String sql = "insert into t_books value(null,?,?,?,?,?)";
        try {
            return qr.update(sql, book.getName(), book.getPrice(), book.getDescription(), book.getAuthor(), book.getPublisher());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int delete(Integer bookId) {
        String sql = "delete  from t_books where id = ?";
        try {
            return qr.update(sql, bookId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int updateOneBook(Integer id, Book book) {
        String sql = "update t_books set name=?,price=?,description=?,author=?,publisher=? where id = ? ";
        try {
            return qr.update(sql, book.getName(), book.getPrice(), book.getDescription(), book.getAuthor(), book.getPublisher(), id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

}
